package org.example.day05;

/**
 * 第二章节2.2.16.2: 锁对象的改变
 *      锁对象不变，锁对象中属性改变，不会影响同步效果。
 */
public class MyThread12 {
    public void serviceMeThodA(UserInfo userInfo){
        synchronized (userInfo){
            try {
                System.out.println(Thread.currentThread().getName());
                userInfo.setUsername("mikasa");
                Thread.sleep(3000);
                System.out.println("end time = " + System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            MyThread12 m12 = new MyThread12();
            UserInfo userInfo = new UserInfo();
            Thread12A ta = new Thread12A(m12,userInfo);
            ta.setName("A");
            ta.start();
            Thread.sleep(100); //确保先进入的线程已经修改了userInfo对象的username属性
            Thread12B tb = new Thread12B(m12, userInfo);
            tb.setName("B");
            tb.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

class Thread12A extends Thread{
    private MyThread12 m12;
    private UserInfo userInfo;

    public Thread12A(MyThread12 m12, UserInfo userInfo) {
        this.m12 = m12;
        this.userInfo = userInfo;
    }

    @Override
    public void run() {
        m12.serviceMeThodA(userInfo);
    }
}

class Thread12B extends Thread{
    private MyThread12 m12;
    private UserInfo userInfo;

    public Thread12B(MyThread12 m12, UserInfo userInfo) {
        this.m12 = m12;
        this.userInfo = userInfo;
    }

    @Override
    public void run() {
        m12.serviceMeThodA(userInfo);
    }
}
